package com.sfx.concurrent.demo.concurrent.CountLatch;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 等待多个线程执行完毕
 * 等待多个远程调用完毕
 * 没有返回结果的时候使用countDownLatch比较合适
 * 有返回结果的时候使用future比较合适
 */
@Slf4j(topic = "c.PrePareFinal")
public class PrePareFinal {

    private static final ExecutorService pool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        Random r = new Random();
        String[] str = new String[10];
        for(int j =0;j<10;++j) {
            int k = j;
            pool.submit(() -> {
                for (int i = 0; i <= 100; ++i) {
                    sleeper(r.nextInt(100));
                    str[k] = i + "%";
                    System.out.print("\r" + Arrays.toString(str));
                }
                countDownLatch.countDown();
            });
        }
        pool.shutdown();
        countDownLatch.await();
        System.out.print("\n" + "游戏开始");
    }
    public static void sleeper(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}